<template>
  <div>
    <breadcrumb>
      <span slot="first">首页</span>
      <span slot="second">商品管理</span>
      <span slot="third">分类参数</span>
    </breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon>
          </el-alert>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <span style="font-size: 14px">选择商品分类：</span>
          <el-cascader :options="cascaderData" :props="cascaderProps" v-model="cascaderKeys" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏区域 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button :disabled="isDisabled" type="primary" size="mini" @click="dialogVisible = true">添加参数
              </el-button>
            </el-col>
          </el-row>
          <!-- 表格区域 -->
          <el-table :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="tagClosed(index, scope.row)" closable type="success" v-for="(item, index) in scope.row.attr_vals" v-if="scope.row.attr_vals.length !== 0">
                  {{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" class="el-icon-edit" @click="edit(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" class="el-icon-delete" @click="remove(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button :disabled="isDisabled" type="primary" size="mini" @click="dialogVisible = true">添加属性
              </el-button>
            </el-col>
          </el-row>
          <!-- 表格区域 -->
          <el-table :data="onlyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="tagClosed(index, scope.row)" closable v-for="(item, index) in scope.row.attr_vals" v-if="scope.row.attr_vals.length !== 0">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" class="el-icon-edit" @click="edit(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" class="el-icon-delete" @click="remove(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog @close="dialogClosed" :title="'添加' + titleText" :visible.sync="dialogVisible" width="50%">
      <span>
        <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsButton">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog @close="editDialogClosed" :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%">
      <span>
        <el-form :model="editParams" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { request } from '@/network/request.js'
import Breadcrumb from '@/components/common/Breadcrumb.vue'
export default {
  name: "Params",
  components: {
    Breadcrumb,
  },
  data() {
    return {
      // 级联选择框数据源
      cascaderData: [],
      // 级联选择框配置选项
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      // 级联选择框数据绑定数组
      cascaderKeys: [],
      // tab选择
      activeName: 'many',
      // 动态数据表格
      manyTableData: [],
      // 静态数据表格
      onlyTableData: [],
      // 添加参数对话框显示 隐藏
      dialogVisible: false,
      // 添加参数表单数据源
      addParams: {
        attr_name: "",
        attr_id: ""
      },
      // 添加参数表单验证规则
      addParamsRules: {
        attr_name: [{
          required: true, message: "不能为空", trigger: 'blur',
        }]
      },
      // 控制修改对话框的显示隐藏
      editDialogVisible: false,
      // 修改参数的表单数据绑定
      editParams: {
        attr_name: ""
      },
      // 修改参数的表单数据验证规则
      editParamsRules: {
        attr_name: [{
          required: true, message: "不能为空", trigger: 'blur',
        }]
      },

    }
  },
  methods: {
    // 获取所有的分类列表
    async getCategoryList() {
      const { data: res } = await request("/categories")
      if (res.meta.status !== 200) return
      this.cascaderData = res.data
    },
    // 级联选择框改变事件
    handleChange() {
      if (this.cascaderKeys.length !== 3) {
        this.cascaderKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 获取表格数据
      this.getAllCate()
      // console.log(this.activeForm);
    },
    // tab栏切换
    handleClick() {
      this.getAllCate()
    },
    // 获取参数列表数据源
    async getAllCate() {
      if (this.cascaderKeys.length === 3) {
        const { data: res } = await request({
          url: `categories/${this.cascaderKeys[this.cascaderKeys.length - 1]}/attributes`,
          params: { sel: this.activeName }
        })
        if (res.meta.status !== 200) return this.$message.error("获取表格数据失败")
        res.data.forEach(item => {
          if (item.attr_vals === "") item.attr_vals = []
          else item.attr_vals = item.attr_vals.split(",")
          item.inputVisible = false
          item.inputValue = ""
        })
        if (this.activeName === "many") {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
          console.log(this.onlyTableData);
        }
      }
    },
    // 添加参数确定按钮
    addParamsButton() {
      // 进行表单预验证
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return
        // 发送网络请求
        const { data: res } = await request({
          method: "post",
          url: `categories/${this.cascaderKeys[this.cascaderKeys.length - 1]}/attributes`,
          data: {
            attr_name: this.addParams.attr_name,
            attr_sel: this.activeName
          }
        })
        if (res.meta.status !== 201) return
        this.$message.success("添加参数成功")
        this.getAllCate()
        this.dialogVisible = false
      })

    },
    // 添加参数对话框关闭事件
    dialogClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 修改对话框关闭事件
    editDialogClosed() {
      this.$refs.editParamsRef.resetFields()
    },
    // 修改参数确定按钮
    editParamsButton() {
      // 表单预验证
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return
        console.log(this.editParams);
        // 发送网络请求
        const { data: res } = await request({
          method: "put",
          url: `categories/${this.cascaderKeys[this.cascaderKeys.length - 1]}/attributes/${this.editParams.attr_id}`,
          data: {
            attr_name: this.editParams.attr_name,
            attr_sel: this.activeName
          }
        })
        if (res.meta.status !== 200) return this.$message.error("修改属性失败")
        this.$message.success("修改属性成功")
        this.getAllCate()
        this.editDialogVisible = false
      })
    },
    // 编辑按钮
    edit(scope_row) {
      this.editParams.attr_id = scope_row.attr_id
      this.editParams.attr_name = scope_row.attr_name
      this.editDialogVisible = true
    },
    // 删除按钮
    async remove(scope_row) {
      const flag = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (flag !== 'confirm') return
      // 删除业务逻辑
      else {
        const { data: res } = await request({
          method: "delete",
          url: `categories/${this.cascaderKeys[this.cascaderKeys.length - 1]}/attributes/${scope_row.attr_id}`
        })

        if (res.meta.status !== 200) return this.$message.error("删除参数失败")
        this.getAllCate()
        this.$message.success("删除参数成功")
      }

    },
    // newTag失去焦点触发
    async handleInputConfirm(scope_row) {
      // 输入为空格
      if (scope_row.inputValue.trim().length === 0) {
        scope_row.inputValue = ''
        scope_row.inputVisible = !scope_row.inputVisible
        return
      }
      // 渲染页面
      scope_row.attr_vals.push(scope_row.inputValue)
      // 发送网络请求
      const {data: res} = await request({
        method: "put",
        url: `categories/${this.cascaderKeys[this.cascaderKeys.length - 1]}/attributes/${scope_row.attr_id}`,
        data: {
          attr_name: scope_row.attr_name,
          attr_sel: scope_row.attr_sel,
          attr_vals: scope_row.attr_vals.join(",")
        }
      })
      if (res.meta.status !== 200) return this.$message.error("New Tag Error")
      this.$message.success("New Tag Success")
      scope_row.inputVisible = !scope_row.inputVisible

    },
    // 点击展示input
    showInput(scope_row) {
      scope_row.inputVisible = !scope_row.inputVisible
      // 输入框自动获得焦点
      this.$nextTick(_ => {
        scope_row.inputValue = ''
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除Tag触发
    async tagClosed(index, scope_row) {
      scope_row.attr_vals.splice(index, 1)
      // 发送网络请求
      const { data: res } = await request({
        method: "put",
        url: `categories/${this.cascaderKeys[this.cascaderKeys.length - 1]}/attributes/${scope_row.attr_id}`,
        data: {
          attr_name: scope_row.attr_name,
          attr_sel: scope_row.attr_sel,
          attr_vals: scope_row.attr_vals.join(",")
        }
      })
      if (res.meta.status !== 200) return this.$message.error("Delete Tag Error")
      this.$message.success("Delete Tag Success")
    }
  },
  computed: {
    isDisabled() {
      return this.cascaderKeys.length === 3 ? false : true
    },
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  created() {
    this.getCategoryList()
  },
}
</script>

<style lang='less' scoped>
.el-alert {
  margin-bottom: 15px;
}

.el-tabs {
  margin-top: 25px;
}

.el-tag {
  margin: 10px 10px;
}
.input-new-tag {
  width: 90px;
}
</style>